<template>
  <view class="app-layout">
    <app-header title="库存配置" />
    <view class="app-main">
      <view class="goods-container">
        <view class="remind">
          <image src="../../static/imgs/icon.png" mode=""></image>
          <text>开启自动置满商品，每日将按设定时间置满商品当前库存和上架商品(手动清零商品)</text>
        </view>
        <view class="goods-title">
          <uni-row :gutter="10">
            <uni-col :span="limit==1?4:6">
              <view style="display: flex;">
                <text class="label-tit"> 商品是否限量:</text>
                <u-switch v-model="limit" size="20" :activeValue="1" :inactiveValue="0"
                  activeColor="#20D048"></u-switch>
              </view>
            </uni-col>
            <uni-col :span="4" v-if="limit==1">
              <uni-easyinput placeholder="可售库存" clearable type="number" v-model="inventory">

              </uni-easyinput>

            </uni-col>
            <uni-col :span="limit==1?5:7">
              <view style="display: flex;">
                <text class="label-tit"> 每日是否自动置满:</text>
                <u-switch v-model="fillup" size="20" :activeValue="1" :inactiveValue="0"
                  activeColor="#20D048"></u-switch>
              </view>

            </uni-col>
            <uni-col :span="4" v-if="limit==1">
              <uni-easyinput placeholder="重置可售量（件）" type="number" clearable v-model="sellable">
              </uni-easyinput>
            </uni-col>
            <uni-col :span="limit==1?4:6">
              <view class="" @click="openPicker('all')">
                <uni-easyinput disabled :styles="{ disableColor: '#fff' }" placeholderStyle="color: #333"
                  v-model="allval" placeholder="商品置满时间" suffixIcon="down"
                  suffixIconStyle="font-size:12px"></uni-easyinput>
              </view>

            </uni-col>
            <uni-col :span="limit==1?3:5">
              <view class="goods-title-btn">
                <view class="order-btn" @click="handelOperate('0')">批量填写</view>

              </view>
            </uni-col>
          </uni-row>
        </view>
        <view class="" style=" flex: 1; overflow: hidden;">
          <scroll-view scroll-y="true" style="height: 100%">

            <view class="form-container">
              <uni-table border stripe :loading="loading" emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th width="50" align="left">商品</uni-th>
                  <uni-th width="100" align="left">商品名称</uni-th>
                  <uni-th width="150" align="left">规格</uni-th>
                  <uni-th width="80" align="left">商品限量</uni-th>
                  <uni-th width="150" align="left"><text class="start">* </text>可售库存（件）</uni-th>
                  <uni-th width="80" align="left">自动置满</uni-th>
                  <uni-th align="left" width="150">重置可售量（件）</uni-th>
                  <uni-th align="left" width="150">每日置满时间</uni-th>
                </uni-tr>
                <uni-tr v-for="(row, rIndex) in tableData" :key="rIndex">
                  <uni-td>
                    <image :src="row.mainImage" mode="widthFix" style="height: 32px;width:32px"></image>
                  </uni-td>
                  <uni-td>
                    <text>{{row.name}}</text>
                  </uni-td>
                  <uni-td>
                    <text>{{row.specComboDesc}}</text>
                  </uni-td>
                  <uni-td>
                    <u-switch v-model="row.limited" size="20" :activeValue="1" :inactiveValue="0" activeColor="#20D048"
                      asyncChange @change="(val) => changeLimited(val, row)"></u-switch>
                  </uni-td>
                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="number" clearable v-model="row.stock"
                      v-if="row.limited==1"></uni-easyinput>
                    <text v-if="row.limited==0">不限量</text>
                  </uni-td>
                  <uni-td>
                    <u-switch v-model="row.syncFlag" size="20" :activeValue="1" :inactiveValue="0" activeColor="#20D048"
                      asyncChange @change="(val) => changesyncFlag(val, row)"></u-switch>
                  </uni-td>
                  <uni-td>
                    <uni-easyinput placeholder="请输入" type="number" clearable v-model="row.targetStock"
                      v-if="row.limited==1">

                    </uni-easyinput>
                    <text v-if="row.limited==0">不限量</text>
                  </uni-td>
                  <uni-td>
                    <view class="" @click="openPicker(rIndex)">
                      <uni-easyinput disabled :styles="{ disableColor: '#fff' }" placeholderStyle="color: #333"
                        v-model="row.refillTime" placeholder="请选择时间点" suffixIcon="down"
                        suffixIconStyle="font-size:12px"></uni-easyinput>
                    </view>
                  </uni-td>

                </uni-tr>
              </uni-table>
            </view>
          </scroll-view>
        </view>
        <u-picker :closeOnClickOverlay="true" :show="showPicker" :columns="columns" title="商品属性模板"
          :defaultIndex="pickerValue" cancelText="取消" @cancel="onClose" @close="showPicker = false"
          @confirm="onConfirm"></u-picker>
        <view class="submit_btncon">
          <view style="display: flex; margin: auto">
            <button class="submit_close" @click="close">取消</button>
            <button class="submit_btn" @click="submit">确定</button>
          </view>
        </view>
      </view>

    </view>
  </view>
</template>
<script setup>
  import {
    ref
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    inventoryPage,
    updateInventory,
  } from '@/requests/apis/products'

  let fillup = ref(0)
  let limit = ref(0)
  let sellable = ref()
  let inventory = ref()
  let allval = ref()
  let tableData = ref()
  const pickerValue = ref([0])
  const columns = ref([
    ['1点', '2点', '3点', '4点', '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点',
      '18点', '19点', '20点',
      '21点', '22点', '23点', '24点'
    ]
  ]);
  let showPopup = ref(false);
  let showPicker = ref(false)
  let titPopup = ref("");
  let typePopup = ref("");
  let infoPopup = ref("")
  let tabindex = ref()
  let loading = ref(true)
  onLoad(async (e) => {
    loading.value = true
    console.log(e, 'eeeeee')
    if (e.spuIds) {
      let spuIds = e.spuIds.split(",")
      let res = await inventoryPage({
        spuIds,
        page: 1,
        limit: 999
      })
      console.log(res.Result)
      tableData.value = res.Result.records || []
      loading.value = false
    }
  })
  const openPicker = (index) => {
    tabindex.value = index
    if (index != 'all') {
      const currentRow = tableData.value[index];
      if (currentRow.refillTime) {
        const hourStr = currentRow.refillTime;
        console.log(hourStr, 'hourStr')
        const hourIndex = columns.value[0].findIndex(item => item === hourStr);
        pickerValue.value = hourIndex !== -1 ? [hourIndex] : [0];
        console.log(pickerValue.value, '11111111111')
      } else {
        pickerValue.value = [0];
      }
    } else {
      const hourIndex = columns.value[0].findIndex(item => item === allval.value);
      pickerValue.value = hourIndex !== -1 ? [hourIndex] : [0];
    }
    showPicker.value = true
  }
  const onConfirm = (e) => {
    showPicker.value = false
    if (tabindex.value != 'all') {
      console.log(1)
      const selectedIndex = e.indexs[0];
      const selectedValue = columns.value[0][selectedIndex];
      tableData.value[tabindex.value].refillTime = selectedValue
    } else {
      const selectedIndex = e.indexs[0];
      const selectedValue = columns.value[0][selectedIndex];
      allval.value = selectedValue
    }
  }
  const onClose = () => {
    showPicker.value = false
    if (tabindex.value != 'all') {
      tableData.value[tabindex.value].refillTime = ''
    } else {
      allval.value = ''
    }
  }
  const handelOperate = () => {
    console.log(fillup.value)
    tableData.value.forEach((row) => {
      row.syncFlag = fillup.value;
      row.limited = limit.value;
      row.targetStock = sellable.value;
      row.stock = inventory.value;
      row.refillTime = allval.value;
    });
  }
  // 点击当前开关

  const changeLimited = (e, row) => {
    row.limited = e
    row.stock = ''
    row.targetStock = ''
  }

  const changesyncFlag = (e, row) => {
    console.log(e, 'eeeeeeeee')
    row.syncFlag = e
    row.refillTime = ''
    row.targetStock = ''
  }

  const submit = async () => {
    const integerReg = /^\d+$/;
    let formData = JSON.parse(JSON.stringify(tableData.value))
    // 表单校验
    for (let i = 0; i < formData.length; i++) {
      const item = formData[i];
      const rowNum = i + 1; // 行号（从1开始）
      console.log(item.stock ,'item.stock item.stock ')
      // 1. 商品限量（limited=1）时，可售库存必填且为整数
      if (item.limited === 1) {
       const stockStr = String(item.stock).trim();
         // 校验：空字符串 / 非数字（NaN）
         if (!stockStr || isNaN(Number(stockStr))) {
          uni.showToast({
            title: `请输入可售库存`,
            icon: 'none',
            duration: 2000
          });
          return;
        }
        if (!integerReg.test(item.stock)) {
          uni.showToast({
            title: `可售库存必须为整数`,
            icon: 'none',
            duration: 2000
          });
          return;
        }
        item.stock = Number(item.stock); // 转换为数字类型
      }

      // 2. 商品不限量（limited=0）时，强制填充默认值
      if (item.limited === 0) {
        item.stock = 99999;
        item.targetStock = 99999;
      }
      if (item.limited === 1) {
        // 若未填写或值为空字符串/undefined，设置为null
        if (item.targetStock === null || item.targetStock === '' || item.targetStock === undefined) {
           item.targetStock = null;
         }
      }

      // 3. 重置可售量（targetStock）：无论是否自动置满，填写了就必须为整数
      // 仅在限量状态下校验（不限量状态已强制填充99999）
      if (item.limited === 1 && item.targetStock !== null && item.targetStock !== undefined && item.targetStock !==
        '') {
        if (isNaN(Number(item.targetStock)) || !integerReg.test(item.targetStock)) {
          uni.showToast({
            title: `重置可售量必须为整数`,
            icon: 'none',
            duration: 2000
          });
          return;
        }
        item.targetStock = Number(item.targetStock); // 转换为数字类型
      }

      // 4. 自动置满（syncFlag=1）时，重置可售量和时间为必填
      if (item.syncFlag === 1) {
        // 4.1 验证重置可售量（限量状态下必须填写）
        if (item.limited === 1 && (!item.targetStock || isNaN(Number(item.targetStock)))) {
          uni.showToast({
            title: `请输入重置可售量`,
            icon: 'none',
            duration: 2000
          });
          return;
        }

        // 4.2 验证每日置满时间
        if (!item.refillTime) {
          uni.showToast({
            title: `请选择每日置满时间`,
            icon: 'none',
            duration: 2000
          });
          return;
        }
      }

    }
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    try {
      const res = await updateInventory({
        configDtoList: formData
      })
      console.log(res, 'resres')
      uni.hideLoading()
      uni.showToast({
        title: res.Result || '',
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 800)
    } catch (error) {
      console.log(error)
    }
  }
  const close = () => {
    uni.navigateBack()
  }
</script>
<style lang="scss" scoped>
  :deep(.is-disabled) {
    color: #333 !important;
  }

  :deep(.u-input) {
    background: #fff !important;
  }

  .form-container {
    padding: 0 20px;
    box-sizing: border-box;
  }

  .goods-container {
    background: #ffffff;
    border-radius: 10px;
    margin: 10px 10px 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    width: 100%;

    .remind {
      padding: 12px 26px;
      box-sizing: border-box;
      background: #F0F6FF;
      border: 1px solid #C4D9F7;

      image {
        width: 14px;
        height: 14px;
      }

      text {
        font-weight: 400;
        font-size: 14px;
        color: #2F4B99;
        margin-left: 12px;
      }
    }

    .goods-title {
      display: flex;
      padding: 20px 20px;
      box-sizing: border-box;
      align-items: center;

      :deep(.uni-row) {
        display: flex;
        align-items: center;
      }

      .label-tit {
        font-weight: 500;
        font-size: 14px;
        color: #333333;
        margin-right: 5px;
      }

      .goods-title-btn {
        display: flex;

        .order-btn {
          border-radius: 8px;
          background: #0F90FD;
          color: #FFFFFF;
          font-weight: 500;
          font-size: 14px;
          padding: 6px 20px;
          box-sizing: border-box;
          margin-right: 10px;
        }
      }
    }
  }
</style>
